import time
import logging

import requests

from conf import config
from helper.meituan.sign_helper import SignHelper
from helper.meituan.request_constant import RequestConstant

logger = logging.getLogger("wechat.helper.meituan")


class CheckOrder(object):
    """
    配送能力校验类：门店配送范围、营业时间
    """
    def __init__(self, shop_id, address, lng, lat, service_code=4011):
        self.shop_id = str(shop_id)
        self.delivery_service_code = service_code
        self.receiver_address = address
        self.receiver_lng = int(lng * pow(10, 6))
        self.receiver_lat = int(lat * pow(10, 6))
        self.coordinate_type = 0
        self.check_type = 1
        self.mock_order_time = int(time.time())
        self.appkey = config.MEITUAN_APP_KEY
        self.secret = config.MEITUAN_APP_SECRET

    def check_order(self):
        secret = self.secret
        data = self.check_order_data()
        sign = SignHelper.get_sign(data, secret)
        logger.info(f"sign={sign}")
        data["sign"] = sign
        url = RequestConstant.ORDER_CHECK_DELIVERY_ABILITY
        try:
            response = requests.post(url, data=data, timeout=30)
            response = response.json()
            logger.info(f"response={response}")
            return response
        except Exception as e:
            logger.error(e)
            return False

    def check_order_data(self):
        data = dict(
            timestamp=int(time.time()),
            version="1.0",
            appkey=self.appkey,
            shop_id=self.shop_id,
            delivery_service_code=self.delivery_service_code,
            receiver_address=self.receiver_address,
            receiver_lng=self.receiver_lng,
            receiver_lat=self.receiver_lat,
            coordinate_type=self.coordinate_type,
            check_type=self.check_type,
            mock_order_time=self.mock_order_time,
        )
        return data


if __name__ == '__main__':
    shop_id = "test_0001"
    address = "深圳市宝安区新安街道宝中卓越时代广场A座14楼"
    lng = 113.8858115673
    lat = 22.5468951747
    o = CheckOrder(shop_id, address, lng, lat)
    result = o.check_order()
    print(f"result={result}")